package com.snail.workflow.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.snail.common.core.utils.StringUtils;
import com.snail.common.redis.service.RedisService;
import com.snail.workflow.api.constant.WorkflowConstants;
import com.snail.workflow.api.domain.entity.WorkflowBusiness;
import com.snail.workflow.mapper.WorkflowBusinessMapper;
import com.snail.workflow.service.IWorkflowBusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @Description: 流程表单信息;(w_workflow_business)表服务实现类
 * @Author: Snail
 * @CreateDate: 2022/7/20 16:47
 * @Version: V1.0
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class WorkflowBusinessServiceImpl extends ServiceImpl<WorkflowBusinessMapper, WorkflowBusiness> implements IWorkflowBusinessService {

    @Autowired
    private RedisService redisService;

    @Override
    public WorkflowBusiness getWorkflowBusinessByBizId(String bizId) {
        //从缓存中获取
        WorkflowBusiness workflowBusiness = redisService.getCacheObject(StringUtils.format(WorkflowConstants.BUSINESS_CACHE_KEY, bizId));
        if (workflowBusiness == null) {
            LambdaQueryWrapper<WorkflowBusiness> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WorkflowBusiness::getBizId, bizId);
            workflowBusiness = getOne(queryWrapper);
        }
        return workflowBusiness;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createWorkflowBusiness(WorkflowBusiness workflowBusiness) {
        workflowBusiness.setWorkflowStatus(WorkflowConstants.STATUS_DRAFT);
        workflowBusiness.setCreateTime(LocalDateTime.now());
        save(workflowBusiness);
        //保存到缓存
        redisService.setCacheObject(StringUtils.format(WorkflowConstants.BUSINESS_CACHE_KEY, workflowBusiness.getWfId()), workflowBusiness);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateWorkflowBusiness(WorkflowBusiness workflowBusiness) {
        this.updateById(workflowBusiness);
        //更新缓存
        redisService.setCacheObject(StringUtils.format(WorkflowConstants.BUSINESS_CACHE_KEY, workflowBusiness.getWfId()), workflowBusiness);
    }
}
